package com.ruyuan.eshop.order.wms;

import com.ruyuan.eshop.common.enums.OrderStatusChangeEnum;
import com.ruyuan.eshop.order.dao.OrderInfoDAO;
import com.ruyuan.eshop.order.dao.OrderOperateLogDAO;
import com.ruyuan.eshop.order.domain.dto.WmsShipDTO;
import com.ruyuan.eshop.order.domain.entity.OrderInfoDO;
import com.ruyuan.eshop.order.exception.OrderBizException;
import com.ruyuan.eshop.order.service.impl.OrderOperateLogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author lxg
 * @Description:
 * @date 2022/4/822:04
 */
public abstract class  AbstractWmsShipResultProcessor implements OrderWmsShipResultProcessor {
    @Autowired
    protected OrderInfoDAO orderInfoDAO;

    @Autowired
    protected OrderOperateLogFactory orderOperateLogFactory;

    @Autowired
    private OrderOperateLogDAO orderOperateLogDAO;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void execute(WmsShipDTO wmsShipDTO) throws OrderBizException {
        //查询订单
        OrderInfoDO orderInfoDO = orderInfoDAO.getByOrderId(wmsShipDTO.getOrderId());
        if (orderInfoDO==null){
            return;
        }
        //2、校验订单状态
        if(!checkOrderStatus(orderInfoDO)) {
            return;
        }
        //3、执行具体的业务逻辑
        doExecute(wmsShipDTO,orderInfoDO);
        //4、更新订单状态
        changeOrderStatus(orderInfoDO,wmsShipDTO);
        //5、增加操作日志
        saveOrderOperateLog(orderInfoDO,wmsShipDTO);
    }

    /**
     * 保存操作日志
     * @param orderInfoDO
     * @param wmsShipDTO
     */
    protected  void saveOrderOperateLog(OrderInfoDO orderInfoDO, WmsShipDTO wmsShipDTO){
        orderOperateLogDAO.save(orderOperateLogFactory.get(orderInfoDO, wmsShipDTO.getStatusChange()));
    }

    /**
     * 更新订单状态
     * @param orderInfoDO
     * @param wmsShipDTO
     */
    private  void changeOrderStatus(OrderInfoDO orderInfoDO, WmsShipDTO wmsShipDTO){
        OrderStatusChangeEnum orderStatusChangeEnum=wmsShipDTO.getStatusChange();
        orderInfoDAO.updateOrderStatus(orderInfoDO.getOrderId(), orderStatusChangeEnum.getPreStatus().getCode(),orderStatusChangeEnum.getCurrentStatus().getCode());
    }

    /**
     * 执行正真的业务逻辑
     * @param wmsShipDTO
     * @param orderInfoDO
     */
    protected abstract void doExecute(WmsShipDTO wmsShipDTO, OrderInfoDO orderInfoDO);

    /**
     * 检查订单状态
     * @param orderInfoDO
     * @return
     */
    protected abstract boolean checkOrderStatus(OrderInfoDO orderInfoDO);
}
